#include "udpsocket.h"
#include <QByteArray>

UdpSocket::UdpSocket(QObject *parent) : QObject(parent)
{
    currentDatas=="aa";
    mdataChanged();
    socket=new QUdpSocket(this);
    listentPort(988);
}

void UdpSocket::listentPort(int port){
//    socket->bind(port);
    socket->bind(QHostAddress::Broadcast,port);
    connect(socket,SIGNAL(readyRead()),this,SLOT(readDatas()));
}

QString UdpSocket::mdata(){
    return currentDatas;
}

void UdpSocket::sendDatas(QString addressk, int port, QString data){
    QHostAddress address(addressk);
    QByteArray datagram;
    datagram.append(data);
    socket->writeDatagram(datagram,address,port);
}

void UdpSocket::readDatas(){
    while (socket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(socket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;
        currentDatas="aa";
        mdataChanged();

        socket->readDatagram(datagram.data(), datagram.size(),
                                &sender, &senderPort);
        currentDatas=datagram.data();
        mdataChanged();
    }
}


